package com.tiger.auth;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AuthorityInterceptor extends HandlerInterceptorAdapter {
	
	private static ThreadLocal<HttpServletResponse> responeHolder = new ThreadLocal<HttpServletResponse>();
	
	
	private NeedLogin getFireAuthority(Object handler) {
		if(handler == null) {
			return null;
		}
		if(!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			return null;
		}
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		return handlerMethod.getMethodAnnotation(NeedLogin.class);
	}
	 
	
	private boolean checkAuthority(NeedLogin check) throws IOException {
		if(check == null) {
			return true;
		}
		Operator me = Operator.me();
		if(me == null) {
			unAuthorized();
			return false;
		}
		return true;
	}
	
	private void unAuthorized() {
		responeHolder.get().setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
	}
	
	private void forbidden() {
		responeHolder.get().setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN);
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		responeHolder.set(response);
		
		NeedLogin fireAuthority = getFireAuthority(handler);
		return checkAuthority(fireAuthority);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		responeHolder.remove();
	}
	
}
